package com.common.base.widget.popup

import android.app.Activity
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.util.TypedValue
import android.view.*
import android.widget.PopupWindow
import com.common.base.R
import com.common.base.utils.AppUtils
import com.common.base.utils.ViewUtils

open class BasePopupWindow(protected var context: Activity?, private val mLayoutId: Int, private val needSetAlpha: Boolean = true
                           , popWidth: Int = ViewGroup.LayoutParams.WRAP_CONTENT, popHeight: Int = ViewGroup.LayoutParams.WRAP_CONTENT) : PopupWindow() {

    private var mLayoutView: View? = null
    private var blackView: View? = null
    private val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    private val mView = ViewUtils.getRootView(context)

    init {
        mLayoutView = View.inflate(context, mLayoutId, null)
        this.contentView = mLayoutView

        width = popWidth
        height = popHeight
        this.isFocusable = true // 可点击
        // 实例化一个ColorDrawable颜色为半透明(半透明遮罩颜色代码#66000000)
//        setBackground(Color.TRANSPARENT)
        contentView.isFocusable = true
        contentView.isFocusableInTouchMode = true
        animationStyle = R.style.base_pop_anim
        setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        isOutsideTouchable = true
        isTouchable = true
        contentView.setOnKeyListener(object : View.OnKeyListener {
            override fun onKey(v: View?, keyCode: Int, event: KeyEvent?): Boolean {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dismiss()
                    return true
                }
                return false
            }

        })
        setOnDismissListener {
            dismissPop()
            ViewUtils.backgroundAlpha(context, 1f)
        }
    }

    protected open fun initView() {

    }

    /**
     * PopupWindow背景设置
     */
    protected fun setBackground(color: Int) {
        // 实例化一个ColorDrawable颜色为半透明
        val dw = ColorDrawable(color)
        this.setBackgroundDrawable(dw)
    }

    /**
     * 显示在控件正上方
     *
     * @param view     依赖的控件
     * @param marginDp 设置的间距(直接写数字即可，已经做过dp2px转换)
     */
    fun showAtLocationTop(view: View, marginDp: Float) {
        mLayoutView?.apply {
            this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val popupWidth = this.measuredWidth
            val popupHeight = this.measuredHeight
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            showAtLocation(view, Gravity.NO_GRAVITY, location[0] + view.width / 2 - popupWidth / 2, location[1] - popupHeight - dp2px(marginDp))
            update()
        }
    }

    /**
     * 显示在控件正下方
     *
     * @param view     依赖的控件
     * @param marginDp 设置的间距(直接写数字即可，已经做过dp2px转换)
     */
    fun showAtLocationGravityBottom(view: View, marginDp: Float) {
        mLayoutView?.apply {
            this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val popupWidth = this.measuredWidth
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            showAtLocation(view, Gravity.NO_GRAVITY, location[0] + view.width / 2 - popupWidth / 2,
                    location[1] + view.height + dp2px(marginDp))
            update()
        }
    }

    /**
     * 显示在控件下方
     *
     * @param view     依赖的控件
     * @param marginDp 设置的间距(直接写数字即可，已经做过dp2px转换)
     */
    fun showAtLocationBottom(view: View, marginDp: Float) {
        showAsDropDown(view, 0, dp2px(marginDp))
        update()
    }


    /**
     * 显示在控件左方
     *
     * @param view     依赖的控件
     * @param marginDp 设置的间距(直接写数字即可，已经做过dp2px转换)
     */
    fun showAtLocationLeft(view: View, marginDp: Float) {
        mLayoutView?.apply {
            this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val popupWidth = this.measuredWidth
            val popupHeight = this.measuredHeight
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            showAtLocation(view, Gravity.NO_GRAVITY, location[0] - popupWidth - dp2px(marginDp), location[1] + view.height / 2 - popupHeight / 2)
            update()
        }
    }

    /**
     * 显示在控件右方
     *
     * @param view     依赖的控件
     * @param marginDp 设置的间距(直接写数字即可，已经做过dp2px转换)
     */
    fun showAtLocationRight(view: View, marginDp: Float) {
        mLayoutView?.apply {
            this.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
            val popupHeight = this.measuredHeight
            val location = IntArray(2)
            view.getLocationOnScreen(location)
            showAtLocation(view, Gravity.NO_GRAVITY, location[0] + view.width + dp2px(marginDp), location[1] + view.height / 2 - popupHeight / 2)
            update()
        }
    }

    private var activity: Activity? = null
//    private var blurScreenUtils: BlurScreenUtils? = null
    /**
     * 显示模糊的PopupWindow
     */
    fun show(activity: Activity?, bgAlpha: Float = 0.5f) {
        if (needSetAlpha) {
            ViewUtils.backgroundAlpha(activity, bgAlpha)
        } else {
            mView?.removeView(blackView)
            blackView = View(activity)
            blackView?.layoutParams = layoutParams
            blackView?.setBackgroundColor(AppUtils.getColor(R.color.transparent_55))
            mView?.addView(blackView)
        }
        this.activity = activity

//        blurScreenUtils = BlurScreenUtils(activity)
        showAtLocation(contentView, Gravity.BOTTOM, 0, 0)
//        blurScreenUtils?.showPopBlur()
    }

    private fun dismissPop() {
//        blurScreenUtils?.remove()
        mView?.removeView(blackView)
    }

    /**
     * 通过id获得view
     */
    @Suppress("UNCHECKED_CAST")
    fun <T : View> findView(viewId: Int): T? {
        if (mLayoutView == null) {
            mLayoutView = LayoutInflater.from(context).inflate(mLayoutId, null)
        }
        val view: View? = mLayoutView?.findViewById(viewId)
        return view as T?
    }


    private fun dp2px(dpVal: Float): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context?.resources?.displayMetrics).toInt()
    }

}
